package com.example.microinvestmq.config;

import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.HashMap;
import java.util.Map;

@Configuration
public class MyRabbitConfig {
    private final RabbitTemplate rabbitTemplate;

    @Autowired
    public MyRabbitConfig(RabbitTemplate rabbitTemplate) {
        this.rabbitTemplate = rabbitTemplate;
    }

    // 创建订单事件交换机
    @Bean
    public Exchange orderEventExchange() {
        return ExchangeBuilder.directExchange("userOrder.direct").durable(true).build();
    }

    @Bean
    @Qualifier("buyOrderDelayQueue")
    public Queue buyOrderDelayQueue() {
        return QueueBuilder.durable("userBuyOrder.delay.queue")
                .withArgument("x-dead-letter-exchange", "userOrder.direct")
                .withArgument("x-dead-letter-routing-key", "buyOrder.release")
                .build();
    }

    @Bean
    @Qualifier("sellOrderDelayQueue")
    public Queue sellOrderDelayQueue() {
        return QueueBuilder.durable("userSellOrder.delay.queue")
                .withArgument("x-dead-letter-exchange", "userOrder.direct")
                .withArgument("x-dead-letter-routing-key", "sellOrder.release")
                .build();
    }


    // 创建死信队列（买入订单）
    @Bean
    @Qualifier("buyOrderReleaseQueue")
    public Queue buyOrderReleaseQueue() {
        return QueueBuilder.durable("userBuyOrder.release.queue").build();
    }

    // 创建死信队列（卖出订单）
    @Bean
    @Qualifier("sellOrderReleaseQueue")
    public Queue sellOrderReleaseQueue() {
        return QueueBuilder.durable("userSellOrder.release.queue").build();
    }

    // 绑定买入延迟队列到交换机
    @Bean
    public Binding bindingBuyDelayQueue(@Qualifier("buyOrderDelayQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("buyOrder.create").noargs();
    }

    // 绑定卖出延迟队列到交换机
    @Bean
    public Binding bindingSellDelayQueue(@Qualifier("sellOrderDelayQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("sellOrder.create").noargs();
    }

    // 绑定买入死信队列到交换机
    @Bean
    public Binding bindingBuyReleaseQueue(@Qualifier("buyOrderReleaseQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("buyOrder.release").noargs();
    }

    // 绑定卖出死信队列到交换机
    @Bean
    public Binding bindingSellReleaseQueue(@Qualifier("sellOrderReleaseQueue") Queue queue, @Qualifier("orderEventExchange") Exchange exchange) {
        return BindingBuilder.bind(queue).to(exchange).with("sellOrder.release").noargs();
    }
}